package top.ikunikun.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import top.ikunikun.common.Result;
import top.ikunikun.domain.Category;
import top.ikunikun.domain.Dish;
import top.ikunikun.domain.DishFlavor;
import top.ikunikun.domain.Setmeal;
import top.ikunikun.dto.DishDto;
import top.ikunikun.service.CategoryService;
import top.ikunikun.service.DishFlavorService;
import top.ikunikun.service.DishService;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "DishCache", allEntries = true)
    public Result<String> save(@RequestBody DishDto dishDto){
        log.info("新增菜品...");
        dishService.saveWithFlavor(dishDto);
        return Result.success("新增菜品成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<DishDto>> page(int page, int pageSize, String name){
        // 分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        // 条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
        // 排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        // 执行分页查询
        dishService.page(pageInfo,queryWrapper);
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map( item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        dishDtoPage.setRecords(list);
        return Result.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id){
        log.info("根据id查询菜品信息和对应的口味信息...");
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "DishCache", allEntries = true)
    public Result<String> update(@RequestBody DishDto dishDto){
        log.info("修改菜品...");
        dishService.updateWithFlavor(dishDto);
        return Result.success("修改菜品成功");
    }

    /**
     * 根据id查询菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "DishCache",key = "'dish_' + #dish.categoryId")
    public Result<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList = null;
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish != null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        dishDtoList = list.stream().map(item ->{
            DishDto dishdto = new DishDto();
            BeanUtils.copyProperties(item,dishdto);
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> flavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishdto.setFlavors(flavors);
            return dishdto;
        }).collect(Collectors.toList());
        return Result.success(dishDtoList);
    }
    /**
     * 菜品状态更改
     * @param num
     * @param ids
     * @return
     */
    @PostMapping("/status/{num}")
    @CacheEvict(value = "DishCache", allEntries = true)
    public Result<String> change(@PathVariable int num,@RequestParam List<Long> ids){
        switch (num){
            case 0:
                ids.forEach(id -> {
                    Dish setmeal = dishService.getById(id);
                    setmeal.setStatus(0);
                    dishService.updateById(setmeal);
                });
                break;
            case 1:
                ids.forEach(id -> {
                    Dish setmeal = dishService.getById(id);
                    setmeal.setStatus(1);
                    dishService.updateById(setmeal);
                });
                break;
        }
        return Result.success("停售成功");
    }
}
